@extends('common.admin_template')

@section('content')
    <div class="boxWidth">
        @include('common.notice_msg')
        <form method="post" action="{{url('admin/post/save')}}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <input type="hidden" name="Post[id]" id="id" value="{{ isset($Post)?$Post->id:"" }}">
            <input type="hidden" name="Post[content]" id="PostContent">
            <input type="hidden" name="Post[arr]" id="PostTagArr">
            <input type="hidden" name="Post[user_id]" value="{{ isset($Post)?$Post->user_id:$CurrentUser->id }}">
            <div class="row">
                <div class="col-xs-9 boxPaddingLeft">
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>标题</span><i class="glyphicon icon-arrow-left"></i></div>
                        <div class="col-xs-11" id="titleNameBox"><input type="text" class="form-control" id="titleName" name="Post[title]" placeholder="请输入标题" value="{{ isset($Post)?$Post->title:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>封面</span></div>
                        <div class="col-xs-10" id="coverNameBox"><input type="text" class="form-control" id="coverName" name="Post[cover]" placeholder="请输入图片链接或点击右边按钮上传封面图片" value="{{ isset($Post)?$Post->cover:'' }}"></div>
                        <div class="col-xs-1" id="coverImg"><img src="{{asset('img/upload.png')}}" alt=""></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>视频</span></div>
                        <div class="col-xs-10"><input type="text" class="form-control" id="videoName" name="Post[video]" placeholder="视频大小超过5M，建议直接七牛后台上传再填写链接" value="{{ isset($meta)&&isset($meta["video"])?$meta["video"]:'' }}"></div>
                        <div class="col-xs-1" id="coverVideo"><img src="{{asset('img/video.png')}}" alt=""></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>作者</span></div>
                        <div class="col-xs-11" id="authorNameBox"><input type="text" class="form-control" id="authorName" name="Post[author]" placeholder="请输入作者名称" value="{{ isset($Post)?$Post->author:$CurrentUser->name }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>跳转链接</span></div>
                        <div class="col-xs-11" id="authorNameBox"><input type="text" class="form-control" id="authorName" name="Post[toUrl]" placeholder="仅在等级为幻灯片时有效，格式为小程序页面路径，如：view/view?id=10&type=service。(路径不需要'pages/') 不填则默认访问文章原始页面" value="{{ isset($meta)&&isset($meta["toUrl"])?$meta["toUrl"]:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-12">
                            <div class="postBox" contenteditable="true" id="PostContentBox">
                                {!! isset($Post)?$Post->content:''  !!}
                            </div>
                        </div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-2"></div>
                        <div class="col-xs-6"></div>
                        <div class="col-xs-4" id="contentImg"><button><img src="{{asset('img/upload.png')}}">上传图片</button></div>
                    </div>
                    <div class="row editFormItem"></div>
                </div>
                <div class="col-xs-3 boxPaddingRight">
                    <div class="postBtnBox">
                        <div class="row postItem">
                            <div class="col-xs-3 postItemName"><span>状态</span></div>
                            <div class="col-xs-8">
                                <select name="Post[status]" id="postStatus">
                                    <option value="0">待审</option>
                                    <option value="1">通过</option>
                                </select>
                            </div>
                        </div>
                        <div class="row postItem">
                            <div class="col-xs-3 postItemName"><span>等级</span></div>
                            <div class="col-xs-8">
                                <select name="Post[level]" id="postLevel">
                                    <option value="0">普通</option>
                                    <option value="1">置顶</option>
                                    <option value="2">幻灯片</option>
                                </select>
                            </div>
                        </div>
                        <div class="row postItem">
                            <div class="col-xs-3 postItemName"><span>分类</span></div>
                            <div class="col-xs-8">
                                <select name="Post[tag]" id="postTag">
                                    @foreach($pages as $page)
                                        <option value="{{$page->id}}">{{$page->name}}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="row postItem">
                            <div class="col-xs-3 postItemName"><span>小程序</span></div>
                            <div class="col-xs-8">
                                <select name="Post[xcx]" id="postXcx">
                                    @foreach($xcxs as $xcx)
                                        @if($xcx->name=="主页")
                                            <option value="{{$xcx->id}}">{{$xcx->name}}</option>
                                        @endif
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="row postItem">
                            <div class="col-xs-3 postItemName"><span>标签</span></div>
                            <div class="col-xs-8"></div>
                        </div>
                        <div class="row postItem ">
                            <div class="col-xs-1"></div>
                            <div class="col-xs-9 postTagBox">
                                @foreach($tags as $tag)
                                    <div class="row"><input class="postTagInput" type="checkbox" value="{{$tag->id}}"><div class="postTagName">{{$tag->name}}</div></div>
                                @endforeach
                            </div>
                        </div>
                        <div class="row postItemBtn" >
                            <div class="col-xs-8"><button class="btn btn-primary" type="submit" id="formSubmit">发布</button></div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
@stop
@section('js')
    <script src="{{asset('js/bootstrap-datetimepicker.js')}}"></script>
    <script src="{{asset('js/plupload/plupload.full.min.js')}}"></script>
    <script src="{{asset('js/quill.js')}}"></script>
    <script>
        (function () {
            function getId(arr,num) {
                return arr.indexOf(Number(num));
            }
            function hasError(id){
                var str =  $('#'+id).val().replace(/(^\s*)|(\s*$)/g, "");
                if(!str){
                    $('#'+id+'Box').addClass('has-error');
                    return 1;
                }
                return 0;
            }
            function activeChange(value) {
                if(value!='no'){
                    $('#activeChange').show();
                    $('#postItemValueContainer').append('<div class="row editFormItem" id="postItemValueBox">' +
                            '<div class="col-xs-2 postItemName"></div>' +
                            '<div class="row col-xs-10 postItemValue" id="postItemValue">' +
                            '<div class="row"><div class="col-xs-6">名称</div><div class="col-xs-6">值</div></div>' +
                            '</div>' +
                            '</div>');
                    if(value==0){
                        $('#postItemValue').append(
                                '<div class="row">' +
                                '<div class="col-xs-6" id="activeKey_0Box"><input type="text" id="activeKey_0" class="form-control" name="Post[activeKey_0]"></div>' +
                                '<div class="col-xs-6" id="activeValue_0Box"><input type="text" id="activeValue_0" class="form-control" name="Post[activeValue_0]"></div>' +
                                '</div>' +
                                '<div class="row">' +
                                '<div class="col-xs-6" id="activeKey_1Box"><input type="text" id="activeKey_1" class="form-control" name="Post[activeKey_1]"></div>' +
                                '<div class="col-xs-6" id="activeValue_1Box"><input type="text" id="activeValue_1" class="form-control" name="Post[activeValue_1]"></div>' +
                                '</div>');
                    }else if(value=="edit"){
                                @if(isset($meta)&&isset($meta["active"]))
                        {!!'var activeArr = '.$meta["active"]!!}
                        var arr="";
                        for(var k = 0;k<activeArr.key.length;k++){
                            arr +=  '<div class="row">' +
                                    '<div class="col-xs-6" id="activeKey_'+k+'Box"><input type="text" id="activeKey_'+k+'" class="form-control" name="Post[activeKey_'+k+']" value="'+activeArr.key[k]+'"></div>' +
                                    '<div class="col-xs-6" id="activeValue_'+k+'Box"><input type="text" id="activeValue_'+k+'" class="form-control" name="Post[activeValue_'+k+']" value="'+activeArr.value[k]+'"></div>' +
                                    '</div>';
                        }
                        $('#postItemValue').append(arr);
                        @endif
                    }else{
                        var idx = getId(formId,value);
                        if(idx != -1){
                            for(var i=0;i<formArr[idx].item.length;i++){
                                var num = $('#postItemValue .row').length - 1;
                                $('#postItemValue').append(
                                        '<div class="row">' +
                                        '<div class="col-xs-6" id="activeKey_'+num+'Box"><input type="text" id="activeKey_'+num+'" class="form-control" name="Post[activeKey_'+num+']" value="'+formArr[idx].item[i]+'"></div>' +
                                        '<div class="col-xs-6" id="activeValue_'+num+'Box"><input type="text" id="activeValue_'+num+'" class="form-control" name="Post[activeValue_'+num+']"></div>' +
                                        '</div>');

                            }
                        }
                    }
                }else{
                    $('#activeChange').hide();
                }
            }
            function formChange(value) {
                if(value!='no'){
                    $('#postFormContainer').append('<div class="row editFormItem" id="formItemBox">' +
                            '<div class="col-xs-2 postItemName"></div>' +
                            '<div class="row col-xs-10 postItemValue" id="formItemValue">' +
                            '<div class="row"><div class="col-xs-12">表单项目</div></div>' +
                            '</div>' +
                            '</div>');
                    if(value==0){
                        $('#formChange').show();
                        $('#formItemValue').append(
                                '<div class="row">' +
                                '<div class="col-xs-12" id="form_0Box"><input type="text" id="form_0" class="form-control" name="Post[form_0]"></div>' +
                                '</div>' +
                                '<div class="row">' +
                                '<div class="col-xs-12" id="form_1Box"><input type="text" id="form_1" class="form-control" name="Post[form_1]"></div>' +
                                '</div>');
                    }else{
                        $('#formChange').hide();
                        var idx = getId(formId,value);
                        if(idx != -1){
                            for(var i=0;i<formArr[idx].item.length;i++){
                                var num = $('#formItemValue .row').length - 1;
                                $('#formItemValue').append(
                                        '<div class="row">' +
                                        '<div class="col-xs-12" id="form_'+num+'Box"><input type="text" id="form_'+num+'" class="form-control" name="Post[form_'+num+']" value="'+formArr[idx].item[i]+'" readonly></div>' +
                                        '</div>'
                                );

                            }
                        }
                    }
                }else{
                    $('#formChange').hide();
                }
            }
            function getToken() {
                $.ajax({
                    url: '{{asset("qiniu.php")}}',
                    type: "get",
                    success: function (response) {
                        token = response;
                        if(!tokenTime){
                            uploader.init();
                        }
                        tokenTime = Math.round(new Date().getTime()/1000);
                    },
                    error: function () {
                        alert('加载失败')
                    },
                    complete: function () {}
                });
            }
            function upInit() {
                if(Math.round(new Date().getTime()/1000)>(tokenTime+3500)){getToken()}
            }

            var token,tokenTime;
            var id = function(id) {return document.getElementById(id);};
            var editor = new Quill('#PostContentBox', {
                modules: {
                    toolbar: [
                        [{ header: [1, 2, 3, 4, 5, 6, false] }],
                        ['bold', 'italic', 'underline', 'strike', { 'align': [] }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'indent': '-1'}, { 'indent': '+1' }, { 'list': 'bullet' }]
                    ] },
                theme: 'snow'
            });
            var Align = Quill.import('attributors/style/align');
            Align.whitelist = ['right', 'center', 'justify'];
            Quill.register(Align, true);

            var formArr = [
                        @foreach($forms as $form)
                        {!!$form->value.','!!}
                        @endforeach
                    ],
                    formId =[
                        @foreach($forms as $form)
                        {!!$form->id.','!!}
                        @endforeach
                    ];
            var picName = new Date();
            var upType;
            picName = picName.getFullYear().toString()+((picName.getMonth()+1)<10?'0'+(picName.getMonth()+1):(picName.getMonth()+1))+(picName.getDate()<10?'0'+picName.getDate():picName.getDate().toString())+'_'+(picName.getHours()<10?'0'+picName.getHours():picName.getHours().toString())+(picName.getMinutes()<10?'0'+picName.getMinutes():picName.getMinutes().toString())+(picName.getSeconds()<10?'0'+picName.getSeconds():picName.getSeconds().toString());
            $('.postTimeCheck').on('change',function () {
                if($(this).is(":checked")){
                    $('.form_datetime').show()
                }else{
                    $('.form_datetime').hide()
                }
            });
            $(".form_datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii'});

            $('#activeItem').on('change',function () {
                $('#postItemValueBox').remove();
                activeChange($(this).val());
            });

            $('#addActive').on('click',function () {
                var num = $('#postItemValue .row').length - 1;
                $('#postItemValue').append(
                        '<div class="row">' +
                        '<div class="col-xs-6" id="activeKey_'+num+'Box"><input type="text" id="activeKey_'+num+'" class="form-control" name="Post[activeKey_'+num+']"></div>' +
                        '<div class="col-xs-6" id="activeValue_'+num+'Box"><input type="text" id="activeValue_'+num+'" class="form-control" name="Post[activeValue_'+num+']"></div>' +
                        '</div>'
                );
            });
            $('#delActive').on('click',function () {
                var row = $('#postItemValue .row'),
                        num = row.length-1;
                if(num>2){
                    row[num].remove();
                }else{
                    alert('请至少保证两项活动说明')
                }
            });

            $('#formItem').on('change',function () {
                $('#formItemBox').remove();
                formChange($(this).val());
            });

            $('#addForm').on('click',function () {
                var num = $('#formItemValue .row').length - 1;
                $('#formItemValue').append(
                        '<div class="row">' +
                        '<div class="col-xs-12" id="form_'+num+'Box"><input type="text" id="form_'+num+'" class="form-control" name="Post[form_'+num+']"></div>' +
                        '</div>'
                );
            });
            $('#delForm').on('click',function () {
                var row = $('#formItemValue .row'),
                        num = row.length-1;
                if(num>2){
                    row[num].remove();
                }else{
                    alert('请至少保证两项表单项目')
                }
            });

            $('#formSubmit').on('click',function (e) {
                var sub = 0,
                        i = 0,
//                        content = $('#PostContentBox').html().replace(/<div>/g, '').replace(/[ ]+</ig, '<').replace(/<\/div>/g, '<br>').replace(/[\r\n]/g,'').trim(),
                        content = $('.ql-editor').html(),
                        tagGroup = $(".postTagBox input");
                $('#PostContent').val(content);

                if(hasError('titleName'))sub=1;
                if(hasError('coverName'))sub=1;
                if(hasError('authorName'))sub=1;

                if($('#activeItem').val()!='no'){
                    for(i=0;i<$('#postItemValue .row').length - 1;i++){
                        if(hasError('activeKey_'+i))sub=1;
                        if(hasError('activeValue_'+i))sub=1;
                    }
                }

                if($('.postTimeCheck').is(":checked")){
                    if(hasError('postTime'))sub=1;
                }

                if($('#formItem').val()==='0'){
                    for(i=0;i<$('#formItemValue .row').length - 1;i++){
                        if(hasError('form_'+i))sub=1;
                    }
                }

                var tagArr = [],tagValue="";
                for(i =0;i<tagGroup.length;i++){
                    if($(tagGroup[i]).is(":checked")){
                        tagArr.push($(tagGroup[i]).val());
                    }
                }
                if(tagArr.length){
                    tagValue = JSON.stringify(tagArr);
                }
                $('#PostTagArr').val(tagValue);

                if(sub){
                    e.preventDefault();
                }
            });


            $('#coverImg').on('click',function () {
                upType = 'cover';
                upInit()
            });
            $('#coverVideo').on('click',function () {
                upType = 'video';
                upInit()
            });
            $('#contentImg').on('click',function () {
                upType = 'content';
                upInit()
            });

            var uploader = new plupload.Uploader({
                browse_button : ['contentImg','coverImg','coverVideo'],
                runtimes : 'html5,flash,silverlight,html4',
                url : "https://up.qbox.me/",
                flash_swf_url : "{{asset('js/plupload/Moxie.swf')}}",
                silverlight_xap_url : "{{asset('js/plupload/Moxie.xap')}}",
                unique_names : true,
                init: {
                    PostInit: function() {},
                    BeforeUpload:function(up,file){
                        uploader.setOption("multipart_params",{
                            'token': token,
                            'key': picName+ file.id
                        });
                    },
                    FilesAdded: function(up, files) {
                        plupload.each(files, function(file) {
                            if(upType === 'cover'){
                                $('#coverName').val("等待...")
                            }else if(upType === 'video'){
                                $('#videoName').val("等待...")
                            }
                        });
                    },
                    QueueChanged:function(){
                        uploader.start();
                    },
                    UploadProgress: function(up, file) {
                        if(upType === 'cover'){
                            $('#coverName').val(file.percent + "%")
                        }else if(upType === 'video'){
                            $('#videoName').val(file.percent + "%")
                        }
                        if(file.percent==100){
                            if(upType === 'cover'){
                                $('#coverName').val("即将完成")
                            }else if(upType === 'video'){
                                $('#videoName').val("即将完成")
                            }
                        }
                    },
                    FileUploaded:function(up, file, res){
                        if(upType === 'cover'){
                            $('#coverName').val("https://blhd.1demo.com/"+picName+ file.id)
                        }else if(upType === 'content'){
                            $('.ql-editor').append("<img src=\"https://blhd.1demo.com/"+picName+ file.id+"\" />")
                        }else{
                            $('#videoName').val("https://blhd.1demo.com/"+picName+ file.id)
                        }
                    },
                    UploadComplete: function(up, files) {
                        console.log('complete')
                    },
                    Error : function(up, err) {
                        console.log('fail')
                    }
                }
            });
            getToken();

            @if(isset($Post))
                $("#postLevel").val({{$Post->level}});
            $("#postStatus").val({{$Post->status}});
            $("#postTag").val({{$Post->tag}});
            $("#postXcx").val({{$Post->xcx}});
            @endif

            @if(isset($meta)&&isset($meta["active"]))
                $('#activeItem').val(0);
                activeChange('edit');
            @endif

            @if(isset($meta)&&isset($meta["form"]))
                $('#formItem').val({{$meta["form"]}});
                formChange({{$meta["form"]}});
            @endif

            @if(isset($meta)&&isset($meta["activeTime"]))
                $('.form_datetime').show();
            @endif

            @if(isset($tagGroup))
                var group = {{$tagGroup}},
                    tagGroup = $(".postTagBox input");
                for(var i =0;i<tagGroup.length;i++){
                    if(group.indexOf(Number($(tagGroup[i]).val()))!==-1){
                        $(tagGroup[i]).attr("checked", true);
                    }
                }
            @endif

        })();
    </script>
@stop